package com.zhy.generator.codegen.mybatis.javahelper.elements;

import com.zhy.generator.codegen.api.IntrospectedColumn;
import com.zhy.generator.codegen.dom.java.*;
import com.zhy.generator.codegen.mybatis.javahelper.JavaHelperMethodConstant;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.zhy.generator.codegen.util.JavaBeansUtil.*;

/**
 * @author 源
 */
public class PoToVOMethodGenerator extends AbstractJavaHelperMethodGenerator {
    @Override
    public void addHelperElements(TopLevelClass tlc) {

        Method method = new Method(getMethodStr());
        method.setVisibility(JavaVisibility.PUBLIC);
        method.setStatic(true);
        tlc.addMethod(method);

        FullyQualifiedJavaType paramType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        String paramName = getCamelCaseString(paramType.getShortName(), false);
        Parameter p = new Parameter(paramType, paramName);
        method.addParameter(p);
        tlc.addImportedType(paramType);

        FullyQualifiedJavaType voType = new FullyQualifiedJavaType(introspectedTable.getVoType());
        tlc.addImportedType(voType);
        method.setReturnType(voType);

        String voName = getCamelCaseString(voType.getShortName(), false);

        method.addBodyLine(voType.getShortName() + " " + voName + " = new " + voType.getShortName() + "();");
        List<IntrospectedColumn> allColumns = introspectedTable.getAllColumns();
        for (IntrospectedColumn column : allColumns) {
            FullyQualifiedJavaType fqjt = column.getFullyQualifiedJavaType();
            String property = column.getJavaProperty();
            String getterMethodName = getGetterMethodName(property, fqjt);
            String setterMethodName = getSetterMethodName(property);
            method.addBodyLine(voName + "." + setterMethodName + "(" + paramName + "." + getterMethodName + "());");

            String remarks = column.getRemarks();
            if(!StringUtils.isEmpty(remarks) && remarks.startsWith("constant")){
                FullyQualifiedJavaType type = new FullyQualifiedJavaType(introspectedTable.getConsTantType());
                tlc.addImportedType(type);
                String lableSetterMethodName = getSetterMethodName(property+"Lable");
                method.addBodyLine(voName + "." + lableSetterMethodName + "(" + type.getShortName() + "." + getterMethodName + "("+paramName + "." + getterMethodName + "()));");
            }

        }

        method.addBodyLine("return " + voName + ";");
    }

    @Override
    public String getMethodStr() {
        return JavaHelperMethodConstant.PO_TO_VO;
    }
}
